<?php include "inc/conn.php"; ?>
<?php
	// 获取执行程序的代表字符串
	$act = $_GET['action'];
	switch($act){
		case "reg":
			// 注册程序
			// 获取用户填写的注册数据
			$username = $_POST['username'];
			$password = $_POST['password'];
			$repassword = $_POST['repassword'];
			$nickname = $_POST['nickname'];
			// 验证数据是否有效
			if(strlen($username)<6 || strlen($username)>20){
				die("<script>alert('账号必须是6~20个字符');history.go(-1)</script>");
			}
			if(strlen($password)<6 || strlen($password)>20){
				die("<script>alert('密码必须是6~20个字符');history.go(-1)</script>");
			}
			if($password != $repassword){
				die("<script>alert('两次密码不一致');history.go(-1)</script>");
			}
			if(strlen($nickname)<6 || strlen($nickname)>30){
				die("<script>alert('昵称1~30个字符');history.go(-1)</script>");
			}
			// 验证账号的唯一性
			$sql = "select id from user where username = '{$username}'";
			$res=mysqli_query($conn,$sql) or die("执行命令错误".$sql);
			if(mysqli_num_rows($res) == 1){
				die("<script>alert('对不起，来晚了，该账号已被注册！');history.go(-1)</script>");
			}
			// 补齐数据
			// 对密码进行加密
			$password = md5(md5($password));
			$regtime = time();	// 注册时间就是代码执行的时间
			$addr = 0;
			$status = 1;
			// 添加数据到数据库
			$sql = "insert into user(username,password,nickname,regtime,addr,status) ";
			$sql .= "values('{$username}','{$password}','{$nickname}','{$regtime}','{$addr}','{$status}')";
			$res = mysqli_query($conn,$sql) or die("命令写错了2".$sql);
			if($res){
				die("<script>alert('注册成功!');location.href='login.php';</script>");
			}else{
				die("<script>alert('注册失败!');history.go(-1)</script>");
			}
			break;
		case "login":
			// 登录程序
			$username = $_POST['username'];
			$password = $_POST['password'];
			// 验证有效
			if(strlen($username)<6 || strlen($username)>20){
				die("<script>alert('账号必须是6~20个字符');history.go(-1)</script>");
			}
			if(strlen($password)<6 || strlen($password)>20){
				die("<script>alert('密码必须是6~20个字符');history.go(-1)</script>");
			}
			// 验证正确性
			$sql = "select id,password,nickname from user where username = '{$username}'";
			$res=mysqli_query($conn,$sql) or die("执行命令错误".$sql);
			if(mysqli_num_rows($res) == 0){
				die("<script>alert('账号不存在！');history.go(-1)</script>");
			}
			$row = mysqli_fetch_assoc($res);
			$password = md5(md5($password));
			if($password != $row['password']){
				die("<script>alert('密码错误！');history.go(-1)</script>");
			}
			$_SESSION['nickname'] = $row['nickname'];
			$_SESSION['username'] = $username;
			$_SESSION['uid'] = $row['id'];
			die("<script>alert('登录成功');location.href='index.php'</script>");
			
			break;
		case "logout":
			// 退出程序
			unset($_SESSION['uid']);
			unset($_SESSION['nickname']);
			unset($_SESSION['username']);
			echo "<script>alert('退出成功，正在跳转！');location.href='login.php';</script>";
			
			break;
	}


?>